using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MagnoliaTableAdapters;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;


public partial class Users : System.Web.UI.Page
{
    static Magnolia.USERDataTable users = new Magnolia.USERDataTable();
    static CheckBoxList alterBoxList = new CheckBoxList();
    static USERTableAdapter usersAdapter = new USERTableAdapter();
    static bool edit;
    static bool create;

    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - Users";

        // hide edit and new buttons for user access
        Btn_EditUser.Style.Add("display", "none");
        Btn_NewUser.Style.Add("display", "none");

        // get user access permissions
        DataTable UserAccessDT = (DataTable)Session["UserAccess"];
        foreach (DataRow dr in UserAccessDT.Rows)
        {
            // edit user
            if (Convert.ToString(dr.ItemArray[0]) == "321")
            {
                Btn_EditUser.Style.Add("display", "block");
            }
            // new user
            if (Convert.ToString(dr.ItemArray[0]) == "421")
            {
                Btn_NewUser.Style.Add("display", "block");
            }

        }

        //Render the useralert every page load
        RenderUserAlerts();

        if (!Page.IsPostBack)
        {
            //only update the datatable while whole page refresh
            usersAdapter.Fill(users);

            LoadList();

            //Initialize the Usertype table 
            Magnolia.USERTYPEDataTable userTypes = new USERTYPETableAdapter().GetUserTypes();
            DDL_UserType.DataSource = userTypes;
            DDL_UserType.DataTextField = "Name";
            DDL_UserType.DataValueField = "ID";
            DDL_UserType.DataBind();
            FieldDisable();
        }
    }

    //Disable all the editable field
    private void FieldDisable()
    {
        TBox_UserName.Enabled = false;
        TBox_Email.Enabled = false;
        TBox_FirstName.Enabled = false;
        TBox_LastName.Enabled = false;
        TBox_Password.Enabled = false;
        TBox_ConfirmPassword.Enabled = false;
        TBox_Phone.Enabled = false;
        DDL_UserType.Enabled = false;
        alterBoxList.Enabled = false;
        Btn_Save.Enabled = false;
        Btn_EditUser.Enabled = true;
    }

    //Enable the editable field
    private void FieldEnable()
    {
        TBox_UserName.Enabled = true;
        TBox_Email.Enabled = true;
        TBox_FirstName.Enabled = true;
        TBox_LastName.Enabled = true;
        TBox_Password.Enabled = true;
        TBox_ConfirmPassword.Enabled = true;
        TBox_Phone.Enabled = true;
        DDL_UserType.Enabled = true;
        alterBoxList.Enabled = true;
        Btn_Save.Enabled = true;
        Btn_EditUser.Enabled = false;
    }

    //Render the user alert base on the selection 
    protected void RenderUserAlerts()
    {

        Magnolia.ALERTDataTable alerts = new ALERTTableAdapter().GetAlerts();
        //string[] aList = new string[alerts.Rows.Count];

        alterBoxList.CssClass = "row";
        alterBoxList.Style.Add("margin-right", "10px");

        alterBoxList.Items.Clear();//Clear the Controler everytime before reload it

        foreach (Magnolia.ALERTRow alertRow in alerts.Rows)
            alterBoxList.Items.Add(alertRow.Name);
        if(ListBox_Users.SelectedValue !="")
            LoadUserAlerts(Convert.ToInt32(ListBox_Users.SelectedValue));

        //Add the CheckBoxList into the Display Panel
        UserAlerts.Controls.Add(alterBoxList);

    }

    //Load the User List and use ID 1 as default display users
    protected void LoadList()
    {
        ListBox_Users.DataSource = users;
        ListBox_Users.DataTextField = "UserName";
        ListBox_Users.DataValueField = "ID";
        ListBox_Users.DataBind();

        if (users.Rows.Count > 0)
        {
            ListBox_Users.SelectedIndex = 0;
            LoadForm(Convert.ToInt32(ListBox_Users.SelectedValue)); //Load the Form
            Lbl_PageHeader.Text = "User: " + ListBox_Users.SelectedItem.Text;
        }
        else
        {
            ClearForm();
            Lbl_PageHeader.Text = "Users";
            Lbl_EditorAlerts.Visible = false;
        }

        Btn_CancelChanges.Enabled = false;

    }

    //Overload the function with required useID and display Message in the header
    protected void LoadList(int userIndex, string message)
    {
        usersAdapter.Fill(users);
        ListBox_Users.DataSource = users;
        ListBox_Users.DataTextField = "UserName";
        ListBox_Users.DataValueField = "ID";
        ListBox_Users.DataBind();

        if (users.Rows.Count > 0)
        {
            ListBox_Users.SelectedValue = userIndex.ToString();
            LoadForm(Convert.ToInt32(ListBox_Users.SelectedValue));
            Lbl_PageHeader.Text = message;
        }
        else
        {
            ClearForm();
            Lbl_PageHeader.Text = "Users";
            Lbl_EditorAlerts.Visible = false;
        }

        Btn_CancelChanges.Enabled = false;

    }

    //Fill the Form with user information 
    protected void LoadForm(int UserID)
    {
        Hidden_ID.Value = UserID.ToString();
        Magnolia.USERRow userRow = users.FindByID(UserID);

        TBox_UserName.Text = userRow.UserName;
        TBox_FirstName.Text = userRow.FirstName;
        TBox_LastName.Text = userRow.LastName;

        TBox_Email.Text = userRow.Email;
        TBox_Phone.Text = userRow.Phone;
        TBox_UserTypeID.Text = Convert.ToString(userRow.UserTypeID);
        DDL_UserType.SelectedValue = Convert.ToString(userRow.UserTypeID);

        LoadUserAlerts(UserID);
        if (UserAlerts.Controls.Count > 0) UserAlerts.Controls.RemoveAt(0);
        UserAlerts.Controls.Add(alterBoxList);

        Lbl_EditorAlerts.Visible = false;
    }

    //Load the Alerts associated with the selected user
    protected void LoadUserAlerts(int UserID)
    {
        Magnolia.USERALERTDataTable userAlerts = new USERALERTTableAdapter().GetUserAlertsByUserID(UserID);
        //CheckBoxList alterList = (CheckBoxList)UserAlerts.Controls[0];

        foreach (ListItem aList in alterBoxList.Items)
            aList.Selected = false;

        foreach (Magnolia.USERALERTRow userAlertRow in userAlerts.Rows)
            alterBoxList.Items[(userAlertRow.AlertID - 1)].Selected = true;
    }

    //Clear all the editable field
    protected void ClearForm()
    {
        Hidden_ID.Value = "";
        TBox_UserName.Text = "";
        TBox_FirstName.Text = "";
        TBox_LastName.Text = "";
        TBox_Password.Text = "";
        TBox_Email.Text = "";
        TBox_Phone.Text = "";
        TBox_UserTypeID.Text = "";
        Lbl_EditorAlerts.Visible = false;
    }

    //Check the input enter by user
    public bool ValidateInput()
    {
        ArrayList errorList = new ArrayList();
        string strRegex;
        Regex re;

        if (TBox_UserName.Text.Trim() == "")
            errorList.Add("&#149; Username is a required field");
        if (TBox_FirstName.Text.Trim() == "")
            errorList.Add("&#149; First Name is a required field");
        if (TBox_LastName.Text.Trim() == "")
            errorList.Add("&#149; Last Name is a required field");
        if (!edit)
        {
            if (TBox_Password.Text.Trim() == "")
                errorList.Add("&#149; Password is a required field");
        }
        if (TBox_Password.Text != TBox_ConfirmPassword.Text)
            errorList.Add("&#149; Password and Confirm Password do not match. Please try again.");
        if (TBox_Email.Text.Trim() == "")
            errorList.Add("&#149; Email is a required field");
        else
        {
            strRegex = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            re = new Regex(strRegex);
            if (!re.IsMatch(TBox_Email.Text.Trim()))
                errorList.Add("&#149; Email is not formatted correctly");
        }
        if (TBox_Phone.Text.Trim() == "")
            errorList.Add("&#149; Phone is a required field");
        else
        {
            strRegex = @"((\(\d{3}\) ?)|(\d{3}.))?\d{3}.\d{4}";
            re = new Regex(strRegex);
            if (!re.IsMatch(TBox_Phone.Text.Trim()))
                errorList.Add("&#149; Phone is not formatted correctly");
        }
        //If error found, don't save and display error
        if (errorList.Count != 0)
        {
            Lbl_EditorAlerts.Text = "";
            foreach (string msg in errorList)
                Lbl_EditorAlerts.Text += msg + "<BR>";

            Lbl_EditorAlerts.Visible = true;
            return false;
        }
        return true;
    }

    //Save the form
    protected void SaveForm()
    {
        bool passInput = ValidateInput();
        if (!passInput)
            return;

        // Read from form
        USERTableAdapter userAdapter = new USERTableAdapter();
        USERALERTTableAdapter alterAdapter = new USERALERTTableAdapter();
        Magnolia.USERALERTDataTable alterDS = new Magnolia.USERALERTDataTable();
        SHA1 sha = new SHA1CryptoServiceProvider();
        int userID;
        alterAdapter.Fill(alterDS);

        //Check if it is a existing user or new user 
        if (Hidden_ID.Value != "")
        {
            userID = Convert.ToInt32(Hidden_ID.Value);
            Magnolia.USERRow userRow = users.FindByID(userID);
            userRow.UserName = TBox_UserName.Text.Trim();
            userRow.FirstName = TBox_FirstName.Text.Trim();
            userRow.LastName = TBox_LastName.Text.Trim();
            if(TBox_Password.Text != "")
                userRow.Passhash = sha.ComputeHash(Encoding.Unicode.GetBytes(TBox_Password.Text.Trim()));
            userRow.Email = TBox_Email.Text.Trim();
            userRow.Phone = TBox_Phone.Text.Trim();
            userRow.UserTypeID = Convert.ToInt32(DDL_UserType.SelectedValue); //Convert.ToInt32(TBox_UserTypeID.Text.Trim());
            userAdapter.Update(users);


            //Save the list of checked CheckBox
            for (int i = 1; i <= alterBoxList.Items.Count; i++)
            {
                Magnolia.USERALERTRow alterRow = alterDS.FindByAlertIDUserID(i, userID);

                if (alterBoxList.Items[i - 1].Selected && alterRow == null)
                {
                    alterRow = alterDS.NewUSERALERTRow();
                    alterRow.AlertID = i;
                    alterRow.UserID = userID;
                    alterDS.Rows.Add(alterRow);
                    alterAdapter.Update(alterDS);
                }
                else if (!alterBoxList.Items[i - 1].Selected && alterRow != null)
                {
                    alterRow.Delete();
                    alterAdapter.Update(alterDS);
                }
            }
            Lbl_EditorAlerts.Text = "User: \"" + userRow.UserName + "\" successfully saved";
            Lbl_EditorAlerts.Visible = true;
            userID = Convert.ToInt32(ListBox_Users.SelectedValue);
        }
        else  // Insert new user
        {
            Magnolia.USERRow userRow = users.NewUSERRow();
            userRow.UserName = TBox_UserName.Text.Trim();
            userRow.FirstName = TBox_FirstName.Text.Trim();
            userRow.LastName = TBox_LastName.Text.Trim();
            userRow.Passhash = sha.ComputeHash(Encoding.Unicode.GetBytes(TBox_Password.Text.Trim()));
            userRow.Email = TBox_Email.Text.Trim();
            userRow.Phone = TBox_Phone.Text.Trim();
            userRow.ThisEnabled = true;
            userRow.UserTypeID = Convert.ToInt32(DDL_UserType.SelectedValue); //Convert.ToInt32(TBox_UserTypeID.Text.Trim());
            users.Rows.Add(userRow);
            userAdapter.Update(users);
            userID = Convert.ToInt32(userAdapter.GetMaxID());
            //userID = 0;

            alterAdapter.Fill(alterDS);
            for (int i = 1; i <= alterBoxList.Items.Count; i++)
            {
                if (alterBoxList.Items[i - 1].Selected)
                {
                    Magnolia.USERALERTRow alterRow = alterDS.NewUSERALERTRow();
                    alterRow.AlertID = i;
                    alterRow.UserID = userID;
                    alterDS.Rows.Add(alterRow);
                    alterAdapter.Update(alterDS);
                }
            }
            Lbl_EditorAlerts.Text = "User: \"" + userRow.UserName + "\" successfully added";
            Lbl_EditorAlerts.Visible = true;
        }
        //LogActivity(userID);
        Lbl_EditorAlerts.Visible = true;
        EnableList();
        Btn_CancelChanges.Enabled = false;
        LoadList(userID, Lbl_EditorAlerts.Text);
        FieldDisable();
        Btn_EditUser.Enabled = true;
    }

    //Load Activity
    protected void LoadActivity(int userID)
    {

    }

    //Log the activity of the current user 
    protected void LogActivity(int userID)
    {
        ACTIVITYLOGTableAdapter activityLogAdapter = new ACTIVITYLOGTableAdapter();
        int actID = 1000;

        int currentUserID = Convert.ToInt32(Session["UserID"]);

        if (edit)
            actID = 1004;
        else if (create)
            actID = 1000;

        activityLogAdapter.sproc_LogActivity(DateTime.Now, actID, userID, 5, "1", currentUserID);

    }

    //Event to handel when user change the selection 
    protected void ListBox_Users_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ListBox_Users.SelectedValue != "")
        {
            LoadForm(Convert.ToInt32(ListBox_Users.SelectedValue));
            Lbl_PageHeader.Text = "User: " + ListBox_Users.SelectedItem.Text;
            Lbl_EditorAlerts.Visible = false;
        }
    }

    //Save button event
    protected void Btn_Save_Click(object sender, EventArgs e)
    {
        SaveForm();
        edit = false;
        create = false;
    }

    //Edit Button Event
    protected void Btn_EditUser_Click(object sender, EventArgs e)
    {
        edit = true;
        FieldEnable();
        DisableList();
        //LoadForm(Convert.ToInt32(ListBox_Users.SelectedValue));
        Btn_CancelChanges.Enabled = true;
    }

    //Cancel Button Event
    protected void Btn_CancelChanges_Click(object sender, EventArgs e)
    {
        LoadList();
        EnableList();
        FieldDisable();
        Btn_EditUser.Enabled = true;
    }

    //New User Button Event
    protected void Btn_NewUser_Click(object sender, EventArgs e)
    {
        create = true;
        Btn_EditUser.Enabled = false;
        FieldEnable();
        ClearForm();
        ListBox_Users.SelectedIndex = -1;
        Lbl_PageHeader.Text = "User: new user";
        Btn_CancelChanges.Enabled = true;
        DisableList();
        Hidden_ID.Value = "";
        foreach (ListItem lItem in alterBoxList.Items)
            lItem.Selected = false;
    }

    //Reload the user table 
    protected void Btn_Refresh_Click(object sender, EventArgs e)
    {
        ReloadList();
    }

    //REload the table by This.Enabled
    private void ReloadList()
    {
        if (Check_Disabled.Checked)
            usersAdapter.FillBy(users);
        else
            usersAdapter.Fill(users);

        LoadList();
    }

    //Disabled Event
    protected void Check_Disabled_CheckedChanged(object sender, EventArgs e)
    {
        ReloadList();
    }

    //Disable Button Event
    protected void Btn_Disable_Click(object sender, EventArgs e)
    {
        AbleUser(false);
    }

    //Enable Button Event
    protected void Btn_Enable_Click(object sender, EventArgs e)
    {
        AbleUser(true);
    }

    //Disable the List
    protected void DisableList()
    {
        ListBox_Users.Enabled = false;
        ListBox_Users.BackColor = System.Drawing.Color.LightGray;
        Check_Disabled.Enabled = false;
        Btn_Disable.Enabled = false;
        Btn_Enable.Enabled = false;
    }

    //Enable the list
    protected void EnableList()
    {
        ListBox_Users.Enabled = true;
        ListBox_Users.BackColor = System.Drawing.Color.White;
        Check_Disabled.Enabled = true;
        Btn_Disable.Enabled = true;
        Btn_Enable.Enabled = true;
    }

    //Disable or Enable the user base on the give decision parameter
    private void AbleUser(bool decision)
    {
        int userID = Convert.ToInt32(Hidden_ID.Value);
        Magnolia.USERRow userRow = users.FindByID(userID);
        userRow.ThisEnabled = decision;
        usersAdapter.Update(users);
        if (decision)
            LoadList(userID - 1, "User: \"" + userRow.UserName + "\" successfully enabled");
        else
            Lbl_PageHeader.Text = "User: \"" + userRow.UserName + "\" successfully disabled";
    }
}
